package crawer.datatransaction.extend;

import crawer.datatransaction.basic.Pattern;
import crawer.datatransaction.basic.PatternFactory;
import crawer.datatransaction.util.*;
import crawer.util.LogCode;

import java.util.Hashtable;

import javax.swing.tree.DefaultMutableTreeNode;

public class Store extends Pattern {
	public void finalize() {
		instanceCount--;
		// System.out.println("Store release"+instanceCount);
	}

	public Store(PatternFactory p_Factory) {
		super(p_Factory);
		super.userObject = new NodeData(Data.Store, Data.Store,
				NodeData.WithoutRetureValue);
	}

	public Object Operate(String p_DataStream, String p_strUrl,
			Hashtable p_PreData) {
		Hashtable _dataTable = null;
		if (p_PreData != null)
			_dataTable = (Hashtable) p_PreData.clone();
		DefaultMutableTreeNode[] subNodes = super.getAllSubNodes();
		for (DefaultMutableTreeNode sub : subNodes) {
			NodeData nd = super.getNodeData(sub);
			if (nd.getStoreType() == NodeData.WithRetrunValue) {
				Pattern p = (Pattern) sub;
				AnElement _element = (AnElement) p.Operate(p_DataStream,
						p_strUrl, p_PreData);
				if (_element != null && _element.value != null) {
					if (_dataTable == null)
						_dataTable = new Hashtable();
					_dataTable.put(_element.name, _element.value);
				} else {
					return null;
				}
			}
		}
		try {
			m_Factory.StoreManager.store(p_strUrl, _dataTable);
			_dataTable.clear();
			_dataTable = null;
		} catch (Exception e) {
			log.debug(e);
			log.error("[[" + LogCode.E_STORE_FAIL + "]], URL:[" + p_strUrl + "]");
		}
		return null;

	}
}
